import React, { useState, useEffect, useCallback } from "react";
import { Modal, Alert, Form, Radio, Button, Upload, Card, Switch, message } from "antd";
import { DeleteOutlined, FormOutlined, SettingTwoTone, FolderOpenTwoTone } from "@ant-design/icons";
import SetItem from "../../SetItem";
import { CommonModal } from "@/views/components/CommonModal";
import Iconfont from "@/components/IconFont";
import { useExportTask } from "@/views/hooks/useExportTask";
import { useImportTask } from "@/views/hooks/useImportTask";

import ProgressModal from "@/views/components/UIModal/ProgressModal";
import ImportResultModal from "@/views/components/UIModal/ImportResultModal";
import { getImportTemplateUrl, quickQueryLabelGetByCode, quickQueryLabelSaveOrUpdate } from "../../../service";
import { getCurrentUser } from "@/utils/authority";
const storage = window.localStorage; //全局的本地缓存
const { Dragger } = Upload;

const SEARCH_TABLE_CODE = "SystemGoods" + "ExcelImportModal" + "unset";

const ActionExceilImportModal = ({ createTaskData, onCancel }) => {

	const [visible, setVisible] = useState();
	const { percent, step, result, handleDownload, startTask, clearTimer } = useImportTask();
	const [childVisible, setChildVisible] = useState(false);
	const [loadVisible, setLoadVisible] = useState(false);
	const [title, setTitle] = useState("Excel导入款信息");
	const [footer, setFooter] = useState(false);
	const [file, setFile] = useState();
	const [checked, setChecked] = useState(true);
	const [checked1, setChecked1] = useState(false);
	const [open, setOpen] = useState(false);
	const renderTitle = () => {
		return (
			<div>
				<span>Excel导入款信息</span>
				<Button
					type="text"
					icon={<SettingTwoTone />}
					style={{ position: "absolute", right: "60px" }}
					onClick={() => {
						setChildVisible(true);
					}}
				>
					导入设置
				</Button>
			</div>
		);
	};

	useEffect(() => {
		if (step.first === true) {
			setVisible("ProgressModal");
		}
		if (step.second === true) {
			setVisible("ImportResultModal");
		}
		if (step.first === false || step.second === false || step.third === true) {
			onCancel();
		}
	}, [step]);

	useEffect(() => {
		getSetConfig();
		setOpen(true);
	}, []);

	const onCancelChild = () => {
		setChildVisible(false);
	};
	const onOkChild = () => {
		setConfig({ checked, checked1 });
		setChildVisible(false);
	};
	const getTemplateUrl = () => {
		getImportTemplateUrl({ taskType: 1203 }).then(res => {
			const { data, msg: msg1, message: msg2 } = res;
			if (data && typeof data === "string" && String(data).startsWith("http")) {
				const f = document.createElement("form");
				document.body.appendChild(f);
				const i = document.createElement("input");
				i.type = "hidden";
				f.appendChild(i);
				f.action = data; //下载的url 地址 f.submit();
				f.submit();
			} else {
				message.error(msg1 || msg2 || "下载文件失败");
			}
		});
	};

	const handleOk = useCallback(() => {
		if (!file) {
			message.warning("请选择要导入的Excel文件");
			return;
		}
		const businessParam = JSON.stringify({ isCover: Number(checked), isClear: Number(checked1) });
		const formData = new FormData();
		formData.append("file", file);
		formData.append("taskType", 1203);
		formData.append("businessParam", businessParam);

		startTask(formData);
	}, [file]);
	// 导入失败处理
	const handleImportError = () => {
		setLoadVisible(false);
	};

	// 获取导入设置项
	const getSetConfig = () => {
		quickQueryLabelGetByCode({ code: SEARCH_TABLE_CODE })
			.then(res => {
				const { data, success } = res;
				if (success && data && data.param && typeof data.param === "string") {
					setChecked(JSON.parse(data.param)?.checked);
					setChecked1(JSON.parse(data.param)?.checked1);
				} else {
					setChecked(true);
					setChecked1(false);
				}
			})
			.catch(res => {
				console.error("err:", res);
				setChecked(true);
				setChecked1(false);
			});
	};
	// 设置导入设置项
	const setConfig = API_DATA => {
		quickQueryLabelSaveOrUpdate({ code: SEARCH_TABLE_CODE, param: JSON.stringify(API_DATA) })
			.then(res => {
				const { data, success, msg } = res;
				if (success) {
					message.success(msg || "保存成功");
					setChildVisible(false);
				} else {
					message.warning(msg || "保存失败");
				}
			})
			.catch(res => {
				console.log("quickQueryLabelSaveOrUpdate res", res);
			});
	};


	const DraggerProps = {
		name: "file",
		maxCount: 1,
		multiple: true,
		action: "",
		onChange(info) { },
		onDrop(e) { },
		beforeUpload(f) {
			console.log("beforeUpload", f);
			setFile(f);
			return false;
		}
	};
	return (
		<CommonModal title={{ title: renderTitle() }} open={open} width="528px" okText="保存" onCancel={onCancel} onOk={handleOk}>
			<Alert
				showIcon
				message="下载官方 Excel 模板填写，准确高效。"
				action={
					<Button
						type="primary"
						ghost
						style={{ marginLeft: 10 }}
						onClick={() => {
							getTemplateUrl({ taskType: 1203 });
						}}
					>
						下载模板
					</Button>
				}
				type="info"
			/>
			<div className="sectionContent" style={{ background: "white", borderLeft: 0, borderTop: 0, padding: 0, marginTop: 16 }}>
				<Dragger {...DraggerProps}>
					<div style={{ padding: "25.5px 0" }}>
						<p className="ant-upload-drag-icon">
							<Iconfont type="iconExcel" style={{ fontSize: 40 }} />
						</p>
						<p>点击或将文件拖拽到这里上传,只支持Excel文件</p>
						<p className="light-gray">最大50mb，单次最多5000条商品</p>
					</div>
				</Dragger>
			</div>
			<CommonModal
				title={{ title: "导入设置" }}
				width={528}
				open={childVisible}
				onCancel={onCancelChild}
				onOk={onOkChild}
				okText="保存"
			>
				<div className="sectionContent" style={{ background: "white", borderLeft: 0, borderTop: 0, padding: 0 }}>
					<SetItem
						content="修改商品款式信息时，覆盖修改该款下所有的商品"
						remark="如：导入修改款的成本价，则同时修改款内所有商品的成本价"
						onChange={e => {
							setChecked(e);
						}}
						value={checked}
					/>
					<div style={{ height: 16 }}></div>
					<SetItem
						content="导入的列中包含空值时， 将该值置空"
						remark="商品名称不可置空。开启后，空值将上传并清空原数值"
						onChange={e => {
							setChecked1(e);
						}}
						value={checked1}
					/>
					<div style={{ height: 24 }}></div>
				</div>
				<Modal
					title={title}
					width={528}
					open={loadVisible}
					onCancel={() => {
						setLoadVisible(false);
					}}
					onOk={handleImportError}
					okText="导出失败内容"
					footer={footer}
				></Modal>
			</CommonModal>
			<ProgressModal
				visible={visible === "ProgressModal"}
				type="progress"
				percent={percent}
				title="Excel导入款信息"
				msg="数据提交中..."
				skip
				onCancel={() => {
					{
						onCancel();
						clearTimer();
					}
				}}
			/>
			<ImportResultModal
				visible={visible === "ImportResultModal"}
				result={result}
				handleExportFailed={handleDownload}
				handleCancel={onCancel}
			/>
		</CommonModal>
	);
};

export default ActionExceilImportModal;
